<%@ page contentType="text/html;charset=UTF-8" %>
<%@ include file="/WEB-INF/views/include/taglib.jsp" %>
<script>
    //触发事件
    $('#clinicNo').keydown(function (e) {
        if (e.keyCode == 13) {
            var clinicNo = $("#clinicNo").val();
            if (clinicNo != null && clinicNo != '') {
                $("#mainCenterDiv").load(timestamp('${ctx}/finance/outpRcptMaster/refundCharges?clinicNo=' + clinicNo),function(response,status,xhr){
                    if($("#contentTable tr").length <=1){
                        toastr.warning("暂无退费信息，请至医生处申请退费或至药房处申请退药");
                    }
                });
            } else {
                toastr.warning("请输入门诊号进行查询");
            }
        }
    });
    /**
    *查询明细
* @param rcptMasterId
     */
    function searchItems(serialNo,rcptMasterId){
      $("#payments").load(timestamp('${ctx}/finance/outpRcptMaster/getBillItems?serialNo='+serialNo+'&id='+rcptMasterId));
    }
    /**
     *退费弹出框
     * @param rcptMasterId
     */
    function openRefund(cardNo){
        var cash=0.0;
        var total=0.0;
        var rcptNos = new Array();
        var totalCosts = new Array();
        var rcptNo;
        var costs;
        var serialNos = new Array();
        var serialNo;
        var clinicNo = $("#clinicNo").val();
        var masterId = $("#contentTable input[name=rcptNo]:checked");
        var flag = true;
        var checkTbable = "";
        if(clinicNo==null || clinicNo==""){
            toastr.warning("请输入门诊号");
            return;
        }
        if (masterId.length <= 0) {
            toastr.error("请选择收据号");
            return;
        }
        $("#contentTable tr").each(function () {
            var chk = $(this).find('td').eq(0).find('input');
            if (chk.prop("checked")) {
                rcptNo = $(this).find('td').eq(0).find('input').val();
                serialNo = $(this).find('#serialNo').val();
                costs = $(this).find('#costs').val();
                total+=parseFloat(costs);
                cash+=parseFloat(costs);
                rcptNos.push(rcptNo);
                serialNos.push(serialNo);
                totalCosts.push(costs);
                if (checkTbable == "") {
                    checkTbable = serialNo;
                }
                if (checkTbable != serialNo) {
                    toastr.error("您选择的单据是分科收费单子，请分开退费");
                    flag = false;
                    return false;
                }
            }
        });
        if(flag){
            $("#totalCharges").val(cash);
            $("#refund").val(cash);
            refund = layer.open({
                title: '合计',
                type: 1,
                area: ['35%', '50%'],
                content: $("#refundCosts"),
                btn: ['确定', '取消'],
                yes: function (index, layero) {
                    refundCharges(rcptNos,totalCosts,clinicNo,serialNos,cardNo,cash);
                },
                end:function (){
                    $("#change").val("");
                    $("#costsMon").val("");
                    $("input[name=payMoney]").val("");
                }
            });
        }

    }
    /**
    *确认退费
     */
    function refundCharges(rcptNos,totalCosts,clinicNo,serialNos,cardNo,cash){
        if(giveChange()){
            var payType = "";
            var payMoney = "";
            var totalMoney = 0.0;
            var payTypes=$("select[name=payType]");
            for(var i=0;i<payTypes.length;i++){
                var type=$(payTypes[i]).val();
                payType+=type+",";
            }
            var payMoneys=$("input[name=payMoney]");
            for(var j=0;j<payMoneys.length;j++){
                var money = $(payMoneys[j]).val();
                totalMoney += Number(money);
                payMoney+=money+",";
            }
            payType=payType.substring(0,payType.length-1);
            payMoney=payMoney.substring(0,payMoney.length-1);
            if (totalMoney < cash) {
                toastr.warning("输入金额小于应退金额");
                return;
            }
            $.ajax({
                type:'post',
                url:'${ctx}/finance/outpRcptMaster/confirmRefund?rcptNos='+rcptNos+'&totalCosts='+totalCosts+'&clinicNo='+clinicNo
                +'&serialNo='+serialNos+'&cardNo='+cardNo+'&payType='+payType+'&payMoney='+payMoney,
                success:function(data){
                    if(data.code=='success'){
                        toastr.success("退费成功");
                        layer.close(refund);
                        $("#mainCenterDiv").load(timestamp('${ctx}/finance/outpRcptMaster/refundCharges?clinicNo=' + clinicNo));
                    }else{
                        toastr.error("退费失败");
                    }
                }
            });
        };
    }
    $(function () {
        //全选
       /* $("#masterId").on('click', function () {
            var isChecked = $(this).prop("checked");
            $("input[name='rcptNo']").prop("checked", isChecked);
        })*/
        //读卡
        $("#readCard").on("click",function(){
            var cardNo=readOneCard();
            if(!cardNo){
                toastr.error("读卡失败");
                return false;
            }
            openRefund(cardNo);
        })
    })
    //添加支付类型
    function addType(staus, i) {
        var idNum = $(i).parent().find("select").length + 1;
        var leftHtml = "";
        leftHtml += '<div class="form-group" id="addType">' +
        '<label class="col-sm-2 control-label" for="payType">支付类型：</label>' +
        '<div class="col-sm-3">' +
        '<select name="payType" id="payType' + idNum + '" class="form-control" data-parsley-required="true">' +
        <c:forEach items="${fns:getDictList('PAY_WAY_DICT')}" var="type">
        <c:choose>
        <c:when test="${type.label=='现金支付'}">
        '<option value="${type.value}" selected="selected">${type.label}</option>' +
        </c:when>
        <c:otherwise>
        '<option value="${type.value}">${type.label}</option>' +
        </c:otherwise>
        </c:choose>
        </c:forEach>
        '</select>' +
        '</div>' +
        '<label class="col-sm-2 control-label" for="payMoney">退款：</label>' +
        '<div class="col-sm-3">' +
        '<input type="number" class="form-control"  name="payMoney" id="payMoney">' +
        '</div>' +
        '<i class="fa fa-minus" style="cursor: pointer" title="删除支付类型" onclick="addType(\'2\',this);"></i>' +
        '</div>';
        if (staus == '1') {
            $(i).parent().after(leftHtml);
            $("#payType" + idNum).select2();
        } else if (staus == '2') {
            $(i).parent().remove();
        }
    }
    //计算找零
    function giveChange() {
        var totalMoney = 0.0;
        var change=0.0;
        $("input[name=payMoney]").each(function () {
            var money = $(this).val();
            totalMoney += Number(money);
        });
        var costs = $("#totalCharges").val(); // 应收
        if (totalMoney == 0 || totalMoney == null) {
            toastr.error("退费金额不能为空");
            return false;
        }
        if (totalMoney < costs) {
            toastr.error("退费金额小于应收金额，请重新退费");
            return false;
        }
        if(totalMoney > costs){
            toastr.error("退费金额大于应收金额，请重新退费");
            return false;
        }
        return true;
    }
</script>
<div class="content-wrap bg-default">
    <div class="wrapper" style="bottom: 50px;">
        <ul class="nav nav-tabs">
            <li class="active">
                <a href="#"   onclick="loadDiv('mainCenterDiv','${ctx}/finance/outpRcptMaster/refundCharges')">门诊退费</a>
            </li>
        </ul>
        <section class="panel panel-default">
            <div class="panel-body">
                    <div class="datatable-top">
                        <div class="pull-left">
                            <form class="form-inline" id="patientInfo">
                                <label>门诊号 ：</label><input name="clinicNo" id="clinicNo" value="${clinicNo}" class="form-control"
                                                           maxlength="100"/>&nbsp;&nbsp;
                                <label>姓名:</label><input name="name" value="${clinicMaster.name}" id="name" class="form-control" maxlength="100"/>&nbsp;&nbsp;
                                <label>性别:</label><input name="sex"  value="${fns:getDictLabels(clinicMaster.sex,'SEX_DICT','')}" id="sex" class="form-control" maxlength="100"/>&nbsp;&nbsp;
                                <label>年龄：</label> <input name="age" value="${clinicMaster.age}" id="age" class="form-control" maxlength="100"/>
                                &nbsp;<input id="btnSubmit" class="btn btn-primary" type="button" value="退费"
                                             onclick="openRefund('');"/>&nbsp;
                                <input id="readCard" class="btn btn-primary" type="button" value="读卡退费" />


                            </form>
                        </div>
                    </div>
            </div>
        </section>
        <div class="row">
            <div class="col-lg-3">
                <section class="panel">
                    <div class="panel-body">
                        <table id="contentTable" class="table table-bordered mg-t datatable" checkbox="true">
                             <thead>
                                <tr>
                                    <th><input type="checkbox" id="masterId"></th>
                                    <th>收据单号</th>
                                    <th>总费用</th>
                                </tr>
                             </thead>
                            <tbody>
                               <c:forEach items="${rcptMaster}" var="rcptMaster">
                                   <tr id="${rcptMaster.serialNo}" onclick="searchItems('${rcptMaster.serialNo}','${rcptMaster.id}')">
                                       <input type="hidden" id="costs" value="${rcptMaster.totalCharges}">
                                       <input type="hidden" id="serialNo" value="${rcptMaster.serialNo}">
                                       <td><input type="checkbox" value="${rcptMaster.rcptNo}" name="rcptNo"></td>
                                       <td>${rcptMaster.rcptNo}</td>
                                       <td>${rcptMaster.totalCharges}</td>
                                   </tr>
                               </c:forEach>
                            </tbody>
                         </table>
                    </div>
                </section>
            </div>
            <div class="col-lg-9" id="payments">
                <jsp:include page="outpRefundRight.jsp"></jsp:include>
            </div>
        </div>
        <div id="refundCosts" style="display: none">
            <div class="col-lg-12 alert alert-success">
                <section class="panel">
                    <div class="panel-body">
                        <form class="form-horizontal" role="form">
                            <div class="form-group">
                                <label class="col-sm-2 control-label" for="totalCharges">合计：</label>

                                <div class="col-sm-3">
                                    <input type="text" class="form-control" id="totalCharges" readonly="true">
                                </div>
                                <label class="col-sm-2 control-label" for="costs">应退：</label>

                                <div class="col-sm-3">
                                    <input type="text" class="form-control" id="refund" readonly="true">
                                </div>
                            </div>
                            <div class="form-group" id="moneyType">
                                <label class="col-sm-2 control-label" for="payType">支付类型：</label>

                                <div class="col-sm-3">
                                    <select name="payType" class="form-control" id="payType">
                                        <c:forEach items="${fns:getDictList('PAY_WAY_DICT')}" var="type">
                                            <c:choose>
                                                <c:when test="${type.label=='现金支付'}">
                                                    <option value="${type.value}"
                                                            selected="selected">${type.label}</option>
                                                </c:when>
                                                <c:otherwise>
                                                    <option value="${type.value}">${type.label}</option>
                                                </c:otherwise>
                                            </c:choose>
                                        </c:forEach>
                                        <%--</c:if>--%>
                                    </select>
                                </div>
                                <label class="col-sm-2 control-label" for="payMoney">退款：</label>
                                <div class="col-sm-3">
                                    <input type="number" id="cashMoney" class="form-control"  name="payMoney" id="payMoney">
                                </div>
                                <i class="fa fa-plus" style="cursor: pointer" title="增加支付类型"
                                   onclick="addType('1',this);"></i>
                            </div>
                        </form>
                    </div>
                </section>
            </div>
        </div>
    </div>
</div>

